package com.fingard.dsp.bank.directbank.abc02;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.BijectionHashMap;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class ABC02BillPoolBase extends ABC02Base {
    //持票人ID查询/插入/更新SQL
    //RESERVE1-成员单位名称   RESERVE2-成员单位ID
    protected static final String INSERTCLIENTID = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,RESERVE1,RESERVE2) values (?,?,?,?);";
    protected static final String SELECTCLIENTID = "SELECT RESERVE2 FROM REQSEQIDMAPPING WHERE RESERVE1=? AND BANKCODE=?;";
    protected static final String UPDATECLIENTID = "UPDATE REQSEQIDMAPPING SET RESERVE2=? WHERE BANKCODE=? AND RESERVE1=?;";

    public static final BijectionHashMap<String, String> ELE_TRANSCODE = new BijectionHashMap<String, String>();

    static {
//        TRE004	提示收票
//        TRE005	撤票
//        TRE006	背书转让
//        TRE007	贴现
//        TRE012	质押
//        TRE013	解质押
//        TRE014	保证
//        TRE015	提示付款
//        TRE017	追索通知
//        TRE018	同意清偿
//        TRE019	撤销
//        TRE020-承兑回复
//        TRE021-收票回复
//        TRE022-背书转让回复
//        TRE029-质押回复
//        TRE030-质押解除回复
//        TRE031-保证回复
//        TRE034-同意清偿回复
        ELE_TRANSCODE.put("3", "TRE004");
        ELE_TRANSCODE.put("1", "TRE005");
        ELE_TRANSCODE.put("4", "TRE006");
        ELE_TRANSCODE.put("10", "TRE007");
        ELE_TRANSCODE.put("5", "TRE012");
        ELE_TRANSCODE.put("12", "TRE015");
        ELE_TRANSCODE.put("13", "TRE017");
        ELE_TRANSCODE.put("14", "TRE018");
        ELE_TRANSCODE.put("6", "TRE013");
    }

    //票据池内相关电票接口，银行要求上送“持票单位ID”
    //持票人ID查询CQRM15（消息类型5420）
    public String getClientId(String bankCode, String accountName) throws Exception {
        WriteBankLogLn("全量查询持票人ID，调用CQRM15接口...");
        //查询全量持票单位ID
        Connection conn = FGBiz.getLocalDbConn();
        boolean ishasClientId = false;//判断全量查询的持票人ID是否有与想要查询客户名称匹配的ID
        StringBuilder returnMsg = new StringBuilder();
        try {
            XmlTextWriter writerXml = new XmlTextWriter();
            ABC02Header header = new ABC02Header();
            header.CCTransCode = "CQRM15";
            header.msgType = "5420";
            header.ReqDateTime = new Date();
            header.ReqSeqNo = reqHeader.transSeqID;
            writeBillPoolCommonHead(writerXml, header);
            writerXml.writeElementString("ClientGroup", "0");//成员单位范围 （0：全部成员单位/1：集中管理成员单位）
            writerXml.writeEndElement();//Hermes
            writerXml.writeStartElement("ap");
            writerXml.writeStartElement("Cmp");
            writerXml.writeElementString("ConFlag", "", true);//是否加入池融资 Y/N(Y表示只查加入了票据池融资的客户;N表示只查未加入票据池融资的客户如果送空表示查询全部
            writerXml.writeEndDocument();

            String[] tmpStrRet = sendToBank(writerXml.toXmlString(), "CQRM15", "CQRM15");

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                        while (tmpBkReader.read("/ap/SClientList/SClientInfo")) {
                            XElement readXElement = tmpBkReader.readedXElement;
                            String clientName = readXElement.getSingleTextNotNull("ClientName").trim();//成员单位名称
                            String clientID = readXElement.getSingleTextNotNull("ClientId").trim();//成员单位ID
                            if (clientName.equals(accountName)) {
                                ishasClientId = true;
                            }
                            Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTCLIENTID, new Object[]{clientName, bankCode});
                            if (map.size() == 0) {
                                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                JDBCHelper.update(conn, INSERTCLIENTID, new Object[]{uuid, bankCode, clientName, clientID});
                            } else {
                                JDBCHelper.update(conn, UPDATECLIENTID, new Object[]{clientID, bankCode, clientName});
                            }
                        }
                    } else {
                        if (!StringHelper.isNullOrEmpty(tmpRetInfo)) {
                            returnMsg.append("持票人ID查询报错：" + tmpRetInfo + ";");
                        } else {
                            returnMsg.append("持票人ID查询报错：" + tmpRetRxtInfo + ";");
                        }
                    }
                } else {
                    returnMsg.append("持票人ID查询报错：" + tmpSbMsg.toString() + ";");
                }
            } else {
                returnMsg.append("持票人ID查询报错：" + tmpStrRet[1] + ";");
            }
        } catch (Exception e) {
            returnMsg.append("持票人ID查询异常，详情查看日志");
            WriteBankLogLn("持票人ID查询报错:" + e.getMessage());
        } finally {
            conn.close();
        }
        if (!ishasClientId) {
            returnMsg.append("调用持票人ID查询CQRM15查询与[" + accountName + "]匹配的客户名称，没有对应的持票人ID");
        }

        if (returnMsg.length() > 0) {
            return returnMsg.toString();
        } else {
            return "";
        }
    }

    public Map<String, String> CQRT14(String account, String actArea, String billCur, String billNo) throws Exception {
        WriteBankLogLn("调用CQRT14接口，查询票据信息");
        Map<String, String> resutlCQRT14 = new HashMap<String, String>();
        ABC02Header header = new ABC02Header();
        XmlTextWriter writer = new XmlTextWriter();

        header.CCTransCode = "CQRT14";
        header.msgType = "1017";
        header.ReqDateTime = new Date();
        header.ReqSeqNo = reqHeader.transSeqID;
        writeBillPoolCommonHead(writer, header);
        try {
            writer.writeElementString("IdNb", billNo);//票据号码
            writer.writeEndElement();
            writer.writeStartElement("Cmp");
            writer.writeElementString("DbAccNo", getAbcAccNo(account));//查询人账号
            writer.writeElementString("DbProv", getAbcAccProv(account, actArea));//查询人省市代码
            String dbCur = convertCurToBank(billCur);
            writer.writeElementString("DbCur", StringHelper.hasAnyChar(dbCur) ? dbCur : "01");//查询人货币码
            writer.writeEndDocument();

            String[] tmpStrRet = sendToBank(writer.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                        resutlCQRT14.put("Result", "0");
                        resutlCQRT14.put("Nam", tmpBkReader.getFirstText("/ap/Hermes/PayeeInfo/ToNam"));//名称
                        resutlCQRT14.put("Typ", tmpBkReader.getFirstText("/ap/Hermes/PayeeInfo/ToTyp"));//类别
                        resutlCQRT14.put("TypNam", tmpBkReader.getFirstText("/ap/Hermes/PayeeInfo/ToTypNam"));//类别名称
                        resutlCQRT14.put("OrgCode", tmpBkReader.getFirstText("/ap/Hermes/PayeeInfo/ToOrgCode"));//组织机构代码
                        resutlCQRT14.put("OpBnk", tmpBkReader.getFirstText("/ap/Hermes/PayeeInfo/ToOpBnk"));//开户行行号
                        resutlCQRT14.put("OpBnkNam", tmpBkReader.getFirstText("/ap/Hermes/PayeeInfo/ToOpBnkNam"));//开户行名称
                        resutlCQRT14.put("ConBnk", tmpBkReader.getFirstText("/ap/Hermes/PayeeInfo/ToConBnk"));//承接行行号
                        resutlCQRT14.put("ConBnkNam", tmpBkReader.getFirstText("/ap/Hermes/PayeeInfo/ToConBnkNam"));//承接行名称
                        resutlCQRT14.put("TrdAttr", tmpBkReader.getFirstText("/ap/Hermes/PayeeInfo/ToTrdAttr"));//行业属性
                        resutlCQRT14.put("IssDat", tmpBkReader.getFirstText("/ap/Hermes/EBInfo/IssDat"));//出票日期
                        resutlCQRT14.put("DueDat", tmpBkReader.getFirstText("/ap/Hermes/EBInfo/DueDat"));//到期日期
                    } else {
                        resutlCQRT14.put("Result", "-1");
                        resutlCQRT14.put("ResultMsg", "调用CQRT14接口，查询票据信息报错：" + StringHelper.joinNotEmpty(";", tmpRetInfo, tmpRetRxtInfo) + ";");
                    }
                } else {
                    resutlCQRT14.put("Result", "-1");
                    resutlCQRT14.put("ResultMsg", "调用CQRT14接口，查询票据信息报错：" + tmpSbMsg.toString() + ";");
                }
            } else {
                resutlCQRT14.put("Result", "-1");
                resutlCQRT14.put("ResultMsg", "调用CQRT14接口，查询票据信息报错：" + tmpStrRet[1] + ";");
            }
        } catch (Exception e) {
            resutlCQRT14.put("Result", "-1");
            resutlCQRT14.put("ResultMsg", "调用CQRT14接口，查询票据信息异常");
            WriteBankLogLn("调用CQRT14接口，查询票据信息异常:" + e.getMessage());
        }
        return resutlCQRT14;
    }

    public XmlTextReader CQRT33( String billNo) throws Exception {
        WriteBankLogLn("调用CQRT33接口，查询票据信息");
        ABC02Header header = new ABC02Header();
        XmlTextWriter writer = new XmlTextWriter();

        header.CCTransCode = "CQRT33";
        header.msgType = "5042";
        header.ReqDateTime = new Date();
        header.ReqSeqNo = reqHeader.transSeqID;
        writeBillPoolCommonHead(writer, header);
        try {
            writer.writeElementString("IdNb", billNo);//票据号码
            writer.writeEndDocument();

            String[] tmpStrRet = sendToBank(writer.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                    if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                        return tmpBkReader;
                    }
                }
            }
        } catch (Exception e) {
            WriteBankLogLn("调用CQRT33接口，查询票据信息异常:" + e.getMessage());
        }
        return null;
    }


    public void writeBillPoolCommonHead(XmlTextWriter xmlTextWriter, ABC02Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.CCTransCode)) {
            throw new Exception("未赋值CCTransCode");
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.ReqSeqNo)) {
            throw new Exception("未赋值ReqSeqNo");
        }
        xmlTextWriter.writeStartDocument();
        xmlTextWriter.writeStartElement("ap");
        xmlTextWriter.writeElementString("CCTransCode", p_bankHeader.CCTransCode);
        xmlTextWriter.writeElementString("ProductID", "ICC");
        xmlTextWriter.writeElementString("ChannelType", "ERP");
        xmlTextWriter.writeElementString("CorpNo", bankFront.org);//企业技监局号码/客户号
        xmlTextWriter.writeElementString("OpNo", bankFront.operator);//企业操作员编号
        xmlTextWriter.writeElementString("AuthNo", "");
        xmlTextWriter.writeElementString("ReqSeqNo", p_bankHeader.ReqSeqNo);
        if (p_bankHeader.ReqDateTime == null) {
            p_bankHeader.ReqDateTime = new Date();
        }
        xmlTextWriter.writeElementString("ReqDate", Format.Date8Format.format(p_bankHeader.ReqDateTime));
        xmlTextWriter.writeElementString("ReqTime", Format.Time6Format.format(p_bankHeader.ReqDateTime));
        xmlTextWriter.writeElementClosed("Sign");


        xmlTextWriter.writeStartElement("Hermes");
        xmlTextWriter.writeStartElement("Head");
        xmlTextWriter.writeElementString("MsgTyp", p_bankHeader.msgType);
        xmlTextWriter.writeEndElement(); //结束head

    }

    public Map<String, String> CQRB02(String billNo) throws Exception {
        WriteBankLogLn("调用CQRB02接口，查询票据信息");
        Map<String, String> resutlCQRB02 = new HashMap<String, String>();
        ABC02Header header = new ABC02Header();
        XmlTextWriter writer = new XmlTextWriter();

        header.CCTransCode = "CQRB02";
        header.msgType = "5192";
        header.ReqDateTime = new Date();
        header.ReqSeqNo = reqHeader.transSeqID;
        writeBillPoolCommonHead(writer, header);
        try {
            writer.writeElementString("IdNb", billNo);//票据号码
            writer.writeEndDocument();

            String[] tmpStrRet = sendToBank(writer.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                        resutlCQRB02.put("Result", "0");
                        resutlCQRB02.put("ClientId",tmpBkReader.getFirstText("/ap/Hermes/ClientIds"));//持票单位ID
                        resutlCQRB02.put("Nam", tmpBkReader.getFirstText("/ap/Hermes/CPropsr/CpsrNam"));//质权人名称
                        resutlCQRB02.put("Typ", tmpBkReader.getFirstText("/ap/Hermes/CPropsr/CpsrTyp"));//质权人类别
                        resutlCQRB02.put("OrgCode", tmpBkReader.getFirstText("/ap/Hermes/CPropsr/CpsrOrgCode"));//质权人组织机构代码
                        resutlCQRB02.put("AccNo", tmpBkReader.getFirstText("/ap/Hermes/CPropsr/CpsrAccNo"));//质权人账号
                        resutlCQRB02.put("OpBnk", tmpBkReader.getFirstText("/ap/Hermes/CPropsr/CpsrOpBnk"));//质权人开户行行号
                        resutlCQRB02.put("OpBnkNam", tmpBkReader.getFirstText("/ap/Hermes/CPropsr/CpsrOpBnkNam"));//质权人开户行名称
                        resutlCQRB02.put("IssDat", tmpBkReader.getFirstText("/ap/Hermes/IssDat"));//出票日期
                        resutlCQRB02.put("DueDat", tmpBkReader.getFirstText("/ap/Hermes/DueDat"));//到期日
                    } else {
                        resutlCQRB02.put("Result", "-1");
                        resutlCQRB02.put("ResultMsg", "调用CQRB02接口，查询票据信息报错：" + StringHelper.joinNotEmpty(";", tmpRetInfo, tmpRetRxtInfo) + ";");
                    }
                } else {
                    resutlCQRB02.put("Result", "-1");
                    resutlCQRB02.put("ResultMsg", "调用CQRB02接口，查询票据信息报错：" + tmpSbMsg.toString() + ";");
                }
            } else {
                resutlCQRB02.put("Result", "-1");
                resutlCQRB02.put("ResultMsg", "调用CQRB02接口，查询票据信息报错：" + tmpStrRet[1] + ";");
            }
        } catch (Exception e) {
            resutlCQRB02.put("Result", "-1");
            resutlCQRB02.put("ResultMsg", "调用CQRB02接口，查询票据信息异常");
            WriteBankLogLn("调用CQRB02接口，查询票据信息异常:" + e.getMessage());
        }
        return resutlCQRB02;
    }
}
